package com.zyht.bank.manage.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.wx.core.process.WxApi.getBatchTaggingUrl;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.wx.core.process.HttpMethod;
import com.wx.core.process.WxApi;
import com.wx.entity.SysWxuser;
import com.wx.model.BussinessException;
import com.wx.model.EnumCode;
import com.wx.model.ResObject;
import com.wx.service.SysWxTokenService;
import com.wx.service.SysWxuserService;
import com.wx.util.ExcelUtil;
import com.wx.util.FileUtil;
import com.wx.util.StringUtils;
import com.zyht.bank.entity.AxdCertificateImge;
import com.zyht.bank.entity.AxdCertificateImgeExample;
import com.zyht.bank.entity.AxdCustLoan;
import com.zyht.bank.entity.AxdCustloanInfo;
import com.zyht.bank.entity.AxdOrgInfo;
import com.zyht.bank.entity.AxdOrgInfoExample;
import com.zyht.bank.manage.vo.AxdCustLoanDetail;
import com.zyht.bank.manage.vo.AxdCustLoanVo;
import com.zyht.bank.manage.vo.CertificateInfoVo;
import com.zyht.bank.manage.vo.LoanCheckResultVo;
import com.zyht.bank.manage.vo.LoanCondition;
import com.zyht.bank.manage.vo.OrgInfoVO;
import com.zyht.bank.manage.vo.WxFlagVo;
import com.zyht.bank.manage.vo.WxTagVo;
import com.zyht.bank.service.AxdCertificateImgeService;
import com.zyht.bank.service.AxdCertificateInfoService;
import com.zyht.bank.service.AxdCustLoanService;
import com.zyht.bank.service.AxdOrgInfoService;
import com.zyht.common.AbsManageBaseController;
import com.zyht.common.bean.PropertiesUtilBean.PropertiesUtils;
import com.zyht.common.intercepter.Token;
import com.zyht.common.util.CommonUtils;
import com.zyht.common.util.Page;
import com.zyht.redis.service.RedisService;

/**
* <p>Title:客户贷款信息后台管理 </p>
* <p>Description: </p>
* <p>Company: </p> 
* @author xgx
* @date 2017年7月4日
*/
@Controller
@RequestMapping("admin/loan")
public class AdminLoanController2 extends AbsManageBaseController{
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Resource
	private AxdCustLoanService axdCustLoanService;
	@Resource
	private AxdOrgInfoService axdOrgInfoService;
	@Resource
	private SysWxuserService sysWxuserService;
	@Resource
	private SysWxTokenService sysWxTokenService;
	@Resource
	private AxdCertificateInfoService axdCertificateInfoService;
	@Resource
	private AxdCertificateImgeService axdCertificateImgeService;
	@Resource
	private RedisService redisService;
	@Value("#{propertiesReader[real_phone_file_upload_dir]}")
	private  String phone_file_upload_dir;
	@Value("#{propertiesReader[file_copy_dir]}")
	private  String file_copy_dir;
	@Value("#{propertiesReader[phone_file_upload_url]}")
	private  String phone_file_upload_url;
	@Value("#{propertiesReader[globle_default_wxid]}")
	private  String wxId;
	@RequestMapping("index")
	@Token(save=true)
	public String index(AxdCustLoanVo axdCustLoanVo,Integer currentPage,Model model){
		if(null==axdCustLoanVo){
			axdCustLoanVo=new AxdCustLoanVo();
		}
		
		AxdCustLoanVo axdCustLoanVo2=new AxdCustLoanVo();
		if(StringUtils.isNotEmpty(axdCustLoanVo.getLoanOrgCode())){
			AxdOrgInfoExample examples=new AxdOrgInfoExample();
			examples.createCriteria().andOrgCodeEqualTo(axdCustLoanVo.getLoanOrgCode());
			List<AxdOrgInfo> lists = axdOrgInfoService.list(examples);
			AxdOrgInfo axdOrgInfo=lists.get(0);
			model.addAttribute("orgInfo",axdOrgInfo);
			if(axdOrgInfo.getOrgLevel()==3){
				axdCustLoanVo2.setLoanOrgCode(axdCustLoanVo.getLoanOrgCode());
			}else{
				axdCustLoanVo2.setOrgBranch("%"+axdOrgInfo.getOrgName()+"%");
			}
		 }
		if(StringUtils.isNotEmpty(axdCustLoanVo.getCustName())){
			axdCustLoanVo2.setCustName("%"+axdCustLoanVo.getCustName()+"%");
		 }
		if(StringUtils.isNotEmpty(axdCustLoanVo.getCustPhone())){
			axdCustLoanVo2.setCustPhone("%"+axdCustLoanVo.getCustPhone()+"%");
		 }
		if(StringUtils.isNotEmpty(axdCustLoanVo.getCustIdNum())){
			axdCustLoanVo2.setCustIdNum("%"+axdCustLoanVo.getCustIdNum()+"%");
		 }
		if(StringUtils.isNotEmpty(axdCustLoanVo.getIsLoan())){
			axdCustLoanVo2.setIsLoan(axdCustLoanVo.getIsLoan());
		 }
		if(axdCustLoanVo.getLoanDate()!=null){
			axdCustLoanVo2.setLoanDate(axdCustLoanVo.getLoanDate());
		 }
		if(axdCustLoanVo.getDebtDueDate()!=null){
			axdCustLoanVo2.setDebtDueDate(axdCustLoanVo.getDebtDueDate());
		 }
		if(axdCustLoanVo.getLoanCleanDate()!=null){
			axdCustLoanVo2.setLoanCleanDate(axdCustLoanVo.getLoanCleanDate());
		 }
		if(StringUtils.isNotEmpty(axdCustLoanVo.getIsCheck())){
			axdCustLoanVo2.setIsCheck(axdCustLoanVo.getIsCheck());
		 }
		if(StringUtils.isNotEmpty(axdCustLoanVo.getIsCheckConform())){
			axdCustLoanVo2.setIsCheckConform(axdCustLoanVo.getIsCheckConform());
		 }
		if(StringUtils.isNotEmpty(axdCustLoanVo.getFlag())){
			axdCustLoanVo2.setFlag("%"+axdCustLoanVo.getFlag()+"%");
		 }
		if(StringUtils.isNotEmpty(axdCustLoanVo.getIsBinding())){
			axdCustLoanVo2.setIsBinding(axdCustLoanVo.getIsBinding());
		 }
		if(StringUtils.isNotEmpty(axdCustLoanVo.getIsConcern())){
			axdCustLoanVo2.setIsConcern(axdCustLoanVo.getIsConcern());
		 }
		Integer total = axdCustLoanService.count(axdCustLoanVo2);
		if(null==currentPage || currentPage==0){
			currentPage=1;
		}
		if (!StringUtils.isEmpty(axdCustLoanVo.getIsClear())) {
			axdCustLoanVo2.setIsClear(axdCustLoanVo.getIsClear());	
		}
		String pageSizeStr = PropertiesUtils.getConfig("paganation_page_size");
		int pageSize = Integer.valueOf(pageSizeStr);
		Page<AxdCustLoanVo> page = new Page<AxdCustLoanVo>(total,currentPage,pageSize);
		PageHelper.startPage(currentPage, pageSize);
		List<AxdCustLoanVo> list = axdCustLoanService.getAxdCustLoanVos(axdCustLoanVo2);
		page.setRecordList(list);
		model.addAttribute("page",page);
		model.addAttribute("bean",axdCustLoanVo);
		List<WxTagVo> wxTags = axdCustLoanService.getWxTags();
		model.addAttribute("tags", wxTags);
		return "/banks/manage/custLoan/index2";
	}
	
	//查询网点信息
		@RequestMapping("ins")
		public void institutionsInfo(String keyword, HttpServletRequest request,HttpServletResponse response){
			if(!StringUtils.isEmpty(keyword)){
				AxdOrgInfoExample example = new AxdOrgInfoExample();
				example.createCriteria().andOrgNameLike("%"+keyword+"%");
				List<AxdOrgInfo> list = this.axdOrgInfoService.list(example);
				List<OrgInfoVO> insList = new ArrayList<>(list.size());
				for(AxdOrgInfo bean : list){
					OrgInfoVO vo = new OrgInfoVO();
					vo.setCode(bean.getOrgCode());
					vo.setName(bean.getOrgName());
					insList.add(vo);
				}
				String json = JSON.toJSONString(insList);
				writeJson(response,json);
			}else{
				writeJson(response,"");
			}
		}
	
    //贷款详细信息
	@RequestMapping(value="detailInfo{id}",method=RequestMethod.GET)
	public String detailInfo(@PathVariable("id") Integer id,Model model){
		AxdCustLoanDetail axdCustLoanDetail = axdCustLoanService.getAxdCustLoanDetail(id);
		model.addAttribute("bean", axdCustLoanDetail);
		return "/banks/manage/custLoan/detail";
	}
	
	//用途凭证
	@RequestMapping("certificate/{loanId}")
	public String certificate(@PathVariable("loanId") String loanId,Model model){
		List<CertificateInfoVo> selectCertificateImages = axdCustLoanService.selectCertificateImages(loanId);
		if(selectCertificateImages.size()<1){
			model.addAttribute("msg", "此用户没有上传任何凭证!");
		}else{
			for(CertificateInfoVo certificateInfoVo:selectCertificateImages){
				AxdCertificateImgeExample example=new AxdCertificateImgeExample();
				example.createCriteria().andCertificateInfoIdEqualTo(certificateInfoVo.getCertificateInfoId());
				List<AxdCertificateImge> list = axdCertificateImgeService.list(example);
				certificateInfoVo.setAxdCertificateImge(list);
			}
			model.addAttribute("certificateImages", selectCertificateImages);
		}
		model.addAttribute("imagePath", phone_file_upload_url);
		return "/banks/manage/custLoan/certificate2";
	}	
		
		
	
	//文件的导入
	@RequestMapping("im/{type}")
	public String redirectUploadPage(@PathVariable("type") Integer type,Model model){
		model.addAttribute("importType", type);
		return "/banks/manage/custLoan/import";
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("import")
	public void doImport(MultipartFile file,HttpServletResponse response){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		ResObject res = new ResObject();
		String msg = "";
		String relPath="";
		try {
			relPath = FileUtil.writeLocalFile(file);
			if(relPath==null||relPath.isEmpty()){
				throw new BussinessException("写文件失败");
			}
			
			List<List<String>> cvs = FileUtil.readExcel(relPath);
			if(cvs.size()>5000){
				throw new BussinessException("数据超过5000条,会导致处理速度过慢,请分批上传");
			}
			if(cvs.size()<1){
				throw new BussinessException("数据行为空,请检查文件");
			}
			List<String>[] cvsArray = cvs.toArray(new List[0]);
			
			List<AxdCustLoan> custLoanList = new ArrayList<AxdCustLoan>();
			List<AxdCustloanInfo> custloanInfoList = new ArrayList<AxdCustloanInfo>();
			List<AxdCustLoan> custLoanUpdate = new ArrayList<AxdCustLoan>();
			List<AxdCustloanInfo> custloanInfoUpdate = new ArrayList<AxdCustloanInfo>();
			for (int i = 1; i < cvsArray.length; i++) {
				List<String> list2 = cvsArray[i];
				String isUpdate=StringUtils.isNull(list2.get(18));
				String id=StringUtils.isNull(list2.get(19));
				if(isUpdate.equals("0")&&StringUtils.isEmpty(id)){
					continue;
				}
				
				//贷款信息
				String custName = StringUtils.isToNull(list2.get(0));
				if(StringUtils.isEmpty(custName)){
					throw new BussinessException("数据行标"+(i+1)+"客户姓名不正确,请检查文件");
				}
				String custPhone =StringUtils.isToNull(list2.get(1));
				if(StringUtils.isEmpty(custPhone)|| !StringUtils.isPhone(custPhone)){
					throw new BussinessException("数据行标"+(i+1)+"手机号不正确,请检查文件");
				}
				String custIdNum = StringUtils.isToNull(list2.get(2));
				if(StringUtils.isEmpty(custIdNum)){
					throw new BussinessException("数据行标"+(i+1)+"身份证号不正确,请检查文件");
				}
				String loanOrgCode =list2.get(3);
				/*if(StringUtils.isEmpty(loanOrgCode)){
					throw new BussinessException("数据行标"+(i+1)+"机构码不正确,请检查文件");
				}*/
				
				String orgBranch =StringUtils.isToNull(list2.get(4));
				
				String subBranch =StringUtils.isToNull(list2.get(5));
				/*if(StringUtils.isEmpty(subBranch)){
					throw new BussinessException("数据行标"+(i+1)+"支行不正确,请检查文件");
				}*/
				String creditCode =StringUtils.isToNull(list2.get(6));
				/*if(StringUtils.isEmpty(creditCode)){
					throw new BussinessException("数据行标"+(i+1)+"授权编号不正确,请检查文件");
				}*/
				
				String date1 =StringUtils.isToNull(list2.get(8));
				Date loanDate=null;
				String isLoan=null;
				if(!StringUtils.isEmpty(date1)){
					loanDate=format.parse(date1);
					isLoan="1";
				}
				String date2 =StringUtils.isToNull(list2.get(9));
				Date debtDueDate=null;
				if(!StringUtils.isEmpty(date2)){
					debtDueDate=format.parse(date2);
				}
				String date3 =StringUtils.isToNull(list2.get(13));
				Date loanCleanDate=null;
				if(!StringUtils.isEmpty(date3)){
					loanCleanDate=format.parse(date3);
				}
				
				//贷款的详细信息
				Long debtDueMoney=null;
				if(StringUtils.isNotEmpty(list2.get(7))){
					debtDueMoney =Long.parseLong(StringUtils.isToNull(list2.get(7)));
				}
				Integer debtDueAging=null;
				if(StringUtils.isNotEmpty(list2.get(10))){
					debtDueAging=Integer.parseInt(StringUtils.isToNull(list2.get(10)));
				}
				String debtDueKind=StringUtils.isToNull(list2.get(11));
				
				String debtDueUse=StringUtils.isToNull(list2.get(12));
				
				String followManage=StringUtils.isToNull(list2.get(14));
				
				String remark1=null;
				if(list2.size()>16){
					remark1=StringUtils.isToNull(list2.get(16));
				}
				
				String remark2=null;
				if(list2.size()>17){
					remark2=StringUtils.isToNull(list2.get(17));
				}
				
				
				AxdCustLoan axdCustLoan=new AxdCustLoan();
				axdCustLoan.setCustName(custName);
				axdCustLoan.setCustIdNum(custIdNum);
				axdCustLoan.setCustPhone(custPhone);
				axdCustLoan.setLoanOrgCode(loanOrgCode);
				axdCustLoan.setOrgBranch(orgBranch);
				axdCustLoan.setSubBranch(subBranch);
				axdCustLoan.setCreditCode(creditCode);
				axdCustLoan.setIsLoan(isLoan);
				axdCustLoan.setLoanDate(loanDate);
				axdCustLoan.setDebtDueDate(debtDueDate);
				axdCustLoan.setLoanCleanDate(loanCleanDate);
				
				AxdCustloanInfo custloanInfo=new AxdCustloanInfo();
				custloanInfo.setDebtDueMoney(debtDueMoney);
				custloanInfo.setDebtDueAging(debtDueAging);
				custloanInfo.setDebtDueKind(debtDueKind);
				custloanInfo.setDebtDueUse(debtDueUse);
				custloanInfo.setFollowManage(followManage);
				custloanInfo.setRemark1(remark1);
				custloanInfo.setRemark2(remark2);
				Long axdCustLoanId=null;
				if(StringUtils.isEmpty(isUpdate)&&StringUtils.isEmpty(id)){
					axdCustLoanId=redisService.incr("AXD_CUST_LOAN_ID");
					Integer custLoanId=Integer.valueOf(Long.toString(axdCustLoanId));
					axdCustLoan.setLoanId(custLoanId);
					custLoanList.add(axdCustLoan);
					custloanInfo.setLoanId(custLoanId);
					custloanInfoList.add(custloanInfo);
				}
				if(isUpdate.equals("1")&&StringUtils.isNotEmpty(id)){
					axdCustLoan.setLoanId(Integer.valueOf(id));
					custLoanUpdate.add(axdCustLoan);
					custloanInfo.setLoanId(Integer.valueOf(id));
					custloanInfoUpdate.add(custloanInfo);
				}
				
			}
			if(custLoanList==null || custLoanList.isEmpty()){
				throw new BussinessException("数据不正确,请检查文件");
			}
			//插入数据库
			axdCustLoanService.doBatchAdd2(custLoanList,custloanInfoList,custLoanUpdate,custloanInfoUpdate);
			res.setCode(EnumCode.E0000);
			res.setMsg(msg);
			writeHtml(response,JSON.toJSONString(res));
			return;
		} catch (Exception e) {
			msg="系统异常，导入失败";
			e.printStackTrace();
			if(e instanceof BussinessException){
				msg = e.getMessage();
			}
		}finally{
			if(new File(relPath).exists()){
				new File(relPath).delete();
			}
		}
		res.setMsg(msg);
		res.setCode(EnumCode.E1000);
		writeHtml(response,JSON.toJSONString(res));
		return;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("import/update")
	public void doImportUpdate(MultipartFile file,HttpServletResponse response){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ResObject res = new ResObject();
		String msg = "";
		String relPath="";
		try {
			relPath = FileUtil.writeLocalFile(file);
			if(relPath==null||relPath.isEmpty()){
				throw new BussinessException("写文件失败");
			}
			
			List<List<String>> cvs = FileUtil.readExcel(relPath);
			if(cvs.size()>5000){
				throw new BussinessException("数据超过5000条,会导致处理速度过慢,请分批上传");
			}
			if(cvs.size()<1){
				throw new BussinessException("数据行为空,请检查文件");
			}
			List<String>[] cvsArray = cvs.toArray(new List[0]);
			
			List<LoanCheckResultVo> custLoanList = new ArrayList<LoanCheckResultVo>();
			List<LoanCondition> loanConList = new ArrayList<LoanCondition>();
			for (int i = 1; i < cvsArray.length; i++) {
				List<String> list2 = cvsArray[i];
				String isCheckConform = StringUtils.isNull(list2.get(3));
				if(StringUtils.isEmpty(isCheckConform)){
					throw new BussinessException("数据行标"+(i+1)+"凭证是否符合不正确,请检查文件");
				}
				String checkReply =StringUtils.isNull(list2.get(4));
				
				String date =StringUtils.isNull(list2.get(20));
				String loanId =StringUtils.isNull(list2.get(24));
				if(StringUtils.isEmpty(loanId)){
					throw new BussinessException("数据行标"+(i+1)+"ID不正确,请检查文件");
				}
				Date modifyDate=null;
				if(!StringUtils.isEmpty(date)){
					modifyDate=format.parse(date);
				}
				
				LoanCheckResultVo bean=new LoanCheckResultVo();
				bean.setCreditCode(loanId);
				bean.setIsCheckConform(isCheckConform);
				bean.setCheckReply(checkReply);
				
				LoanCondition pojo=new LoanCondition();
				pojo.setCreditCode(loanId);
				pojo.setExamineStatus(isCheckConform);
				pojo.setAuditOpinion(checkReply);
				pojo.setModifyDate(modifyDate);
				
				custLoanList.add(bean);
				loanConList.add(pojo);
				
			}
			if(custLoanList==null || custLoanList.isEmpty()){
				throw new BussinessException("数据不正确,请检查文件");
			}
			//插入数据库
			axdCustLoanService.doBatchUpdate(custLoanList,loanConList);
			res.setCode(EnumCode.E0000);
			res.setMsg(msg);
			writeHtml(response,JSON.toJSONString(res));
			return;
		} catch (Exception e) {
			msg="系统异常，导入失败";
			e.printStackTrace();
			if(e instanceof BussinessException){
				msg = e.getMessage();
			}
		}finally{
			if(new File(relPath).exists()){
				new File(relPath).delete();
			}
		}
		res.setMsg(msg);
		res.setCode(EnumCode.E1000);
		writeHtml(response,JSON.toJSONString(res));
		return;
	}
	
	
	//导出贷款客户信息
	@RequestMapping("ex")
	public void doExport(AxdCustLoanVo axdCustLoanVo,Integer flags, Integer currentPage,HttpServletResponse response) throws IOException{
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<AxdCustLoanDetail> listvo = excuteQuery(axdCustLoanVo,flags,currentPage);
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
	    Map<String, Object> map = new HashMap<String, Object>();
        map.put("sheetName", "sheet1");
        listmap.add(map);
        if(listvo!=null&&listvo.size()>0){
        	for(AxdCustLoanDetail vo:listvo){
        		Map<String, Object> mapValue = new HashMap<String, Object>();
        		mapValue.put("isBinding", null==vo.getIsBinding()||vo.getIsBinding().equals("0")?"否":"是");
        		mapValue.put("isConcern", null==vo.getOpenid()||vo.getOpenid().equals("1")?"否":"是");
        		mapValue.put("isCheck", null==vo.getIsCheck()||vo.getIsCheck().equals("0")?"否":"是");
        		mapValue.put("isCheckConform", vo.getIsCheckConform());
        		mapValue.put("checkReply", vo.getCheckReply());
        		mapValue.put("custName", vo.getCustName());
        		mapValue.put("custPhone", vo.getCustPhone());
        		mapValue.put("custIdNum", vo.getCustIdNum());
        		mapValue.put("loanOrgCode", vo.getLoanOrgCode());
        		mapValue.put("orgBranch", vo.getOrgBranch());
        		mapValue.put("subBranch", vo.getSubBranch());
        		mapValue.put("creditCode", vo.getCreditCode());
        		mapValue.put("debtDueMoney", vo.getDebtDueMoney());
        		mapValue.put("loanDate", null==vo.getLoanDate()?null:sdf.format(vo.getLoanDate()));
        		mapValue.put("debtDueDate", null==vo.getDebtDueDate()?null:sdf.format(vo.getDebtDueDate()));
        		mapValue.put("debtDueAging", vo.getDebtDueAging());
        		mapValue.put("debtDueKind", vo.getDebtDueKind());
        		mapValue.put("debtDueUse", vo.getDebtDueUse());
        		mapValue.put("loanCleanDate", null==vo.getLoanCleanDate()?null:sdf.format(vo.getLoanCleanDate()));
        		mapValue.put("followManage", vo.getFollowManage());
        		mapValue.put("modifyDate", null==vo.getModifyDate()?null:sdf2.format(vo.getModifyDate()));
        		mapValue.put("remark1", vo.getRemark1());
        		mapValue.put("remark2", vo.getRemark2());
        		mapValue.put("isUpdate", "0");
        		mapValue.put("ID", vo.getLoanId());
        		listmap.add(mapValue);
        	}
        }
        //生成excel
        String columnNames[]={"是否关注","是否绑定","是否已回传凭证 ","凭证是否符合0-待审核；1-通过；2-不通过","审核回复","客户姓名","手机号","证件号码","机构码","分行","支行","授信编号","借款金额","放款日期","借款到期日","借款期数","借款种类","借款用途分类","借款结清日期","跟进客服经理","更新凭证时间(无需更改)","其他1","其他2","是否更新数据(0-否，1-是)","ID(无需更改)"};//列名
        String keys[] =  {"isBinding","isConcern","isCheck","isCheckConform","checkReply","custName","custPhone","custIdNum","loanOrgCode","orgBranch","subBranch","creditCode","debtDueMoney","loanDate","debtDueDate","debtDueAging","debtDueKind","debtDueUse","loanCleanDate","followManage","modifyDate","remark1","remark2","isUpdate","ID"};//map中的key
        
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(listmap,keys,columnNames,true).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=ISO8859_1");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String(("ScratchCardsRecord" + ".xls").getBytes(), "ISO8859_1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
	
	}
	
	
	//导出贷款客户凭证
	@RequestMapping("ex/credit")
	public void doExport2(AxdCustLoanVo axdCustLoanVo,Integer flags, Integer currentPage,HttpServletResponse response) throws IOException{
		List<AxdCustLoanDetail> excuteQuery = excuteQuery(axdCustLoanVo,flags,currentPage);
		if(new File(file_copy_dir+"/custLoan.zip").exists()){
			FileUtil.deleteAll(new File(file_copy_dir));
		}
		for(AxdCustLoanDetail detail:excuteQuery){
			FileUtil.copyFolder(new File(phone_file_upload_dir+File.separator+detail.getCustIdNum()+File.separator+"normal"), new File(file_copy_dir+File.separator+detail.getCustIdNum()));
		}
		FileUtil.fileToZip(file_copy_dir,file_copy_dir,"custLoan");
		String filePath=file_copy_dir+"/custLoan.zip";
		BufferedInputStream bis=null;
        BufferedOutputStream  bos=null;
        try{
              String filename=filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length());
              response.setContentType("application/ostet-stream");
              response.setCharacterEncoding("gbk");
              response.setHeader("Content-Disposition","filename="+new String(filename.getBytes("gbk"),"iso8859-1"));
              bis =new BufferedInputStream(new FileInputStream(filePath));
              bos=new BufferedOutputStream(response.getOutputStream()); 
              byte[] buff = new byte[2048];
              int bytesread;
              while(-1 != (bytesread = bis.read(buff, 0, buff.length))) {
               bos.write(buff,0,bytesread);
              }
         }catch(Exception e){
              e.printStackTrace();
         }finally {
          if (bis != null)
             try {
                 bis.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
          if (bos != null)
             try {
                 bos.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
		
	}
	
	
	private List<AxdCustLoanDetail> excuteQuery(AxdCustLoanVo axdCustLoanVo,Integer flags, Integer currentPage){
		if(null==currentPage){
			currentPage = 1;
		}
		
		if(flags==0){
			PageHelper.startPage(currentPage, getPageSize());
		}
		if(null==axdCustLoanVo){
			axdCustLoanVo=new AxdCustLoanVo();
		}
		AxdCustLoanVo axdCustLoanVo2=new AxdCustLoanVo();
		if(StringUtils.isNotEmpty(axdCustLoanVo.getLoanOrgCode())){
			AxdOrgInfoExample examples=new AxdOrgInfoExample();
			examples.createCriteria().andOrgCodeEqualTo(axdCustLoanVo.getLoanOrgCode());
			List<AxdOrgInfo> lists = axdOrgInfoService.list(examples);
			AxdOrgInfo axdOrgInfo=lists.get(0);
			if(axdOrgInfo.getOrgLevel()==3){
				axdCustLoanVo2.setLoanOrgCode(axdCustLoanVo.getLoanOrgCode());
			}else{
				axdCustLoanVo2.setOrgBranch("%"+axdOrgInfo.getOrgName()+"%");
			}
		 }
		if(StringUtils.isNotEmpty(axdCustLoanVo.getCustName())){
			axdCustLoanVo2.setCustName("%"+axdCustLoanVo.getCustName()+"%");
		 }
		if(StringUtils.isNotEmpty(axdCustLoanVo.getCustPhone())){
			axdCustLoanVo2.setCustPhone("%"+axdCustLoanVo.getCustPhone()+"%");
		 }
		if(StringUtils.isNotEmpty(axdCustLoanVo.getCustIdNum())){
			axdCustLoanVo2.setCustIdNum("%"+axdCustLoanVo.getCustIdNum()+"%");
		 }
		if(StringUtils.isNotEmpty(axdCustLoanVo.getIsLoan())){
			axdCustLoanVo2.setIsLoan(axdCustLoanVo.getIsLoan());
		 }
		if(axdCustLoanVo.getLoanDate()!=null){
			axdCustLoanVo2.setLoanDate(axdCustLoanVo.getLoanDate());
		 }
		if(axdCustLoanVo.getDebtDueDate()!=null){
			axdCustLoanVo2.setDebtDueDate(axdCustLoanVo.getDebtDueDate());
		 }
		if(axdCustLoanVo.getLoanCleanDate()!=null){
			axdCustLoanVo2.setLoanCleanDate(axdCustLoanVo.getLoanCleanDate());
		 }
		if(StringUtils.isNotEmpty(axdCustLoanVo.getIsCheck())){
			axdCustLoanVo2.setIsCheck(axdCustLoanVo.getIsCheck());
		 }
		if(StringUtils.isNotEmpty(axdCustLoanVo.getIsCheckConform())){
			axdCustLoanVo2.setIsCheckConform(axdCustLoanVo.getIsCheckConform());
		 }
		if(StringUtils.isNotEmpty(axdCustLoanVo.getFlag())){
			axdCustLoanVo2.setFlag("%"+axdCustLoanVo.getFlag()+"%");
		 }
		if(StringUtils.isNotEmpty(axdCustLoanVo.getIsBinding())){
			axdCustLoanVo2.setIsBinding(axdCustLoanVo.getIsBinding());
		 }
		if (!StringUtils.isEmpty(axdCustLoanVo.getIsClear())) {
			axdCustLoanVo2.setIsCheck(axdCustLoanVo.getIsClear());	
		}
		
		List<AxdCustLoanDetail> listvo = axdCustLoanService.getAxdCustLoanList(axdCustLoanVo2);
		return listvo;
	}
	
	//打标签
	@RequestMapping("makeTag")
	@ResponseBody
	public String makeTag(@RequestParam("openIds") String openIds,@RequestParam("ids") String ids, @RequestParam("tag") String tag,
			HttpServletRequest request,Model model){
		String[] idArray = ids.split(",");
		List<Integer> idList = new ArrayList<>();
		for (String id : idArray) {
			if(!"".equals(id)){
				idList.add(Integer.parseInt(id));
			}
		}
		if(idList.size()>0){
			List<WxFlagVo> wxFlags = axdCustLoanService.getWxFlag(idList);
			for(WxFlagVo wxFlag:wxFlags){
				List<String> tt = CommonUtils.parseList(wxFlag.getFlag());
				tt.add(tag);
				wxFlag.setFlag("," + org.apache.commons.lang.StringUtils.join(tt, ",") + ",");
			}
			
			if (CommonUtils.isNotEmpty(openIds)) {
				List<String> openIdList = CommonUtils.parseList(openIds);
				for(String openid:openIdList){
					if(openid.equals("1")){
						return "error";
					}
				}
				batchAddWechatTag(tag, openIdList, request);
			}else{
				return "error";
			}
			//只更新本地微信标签
			axdCustLoanService.doBatchUpDateFlag(wxFlags);
			return "success";
		}else{
			return "error";
		}
	} 
	
	//取消标签
	@RequestMapping("removeTag")
	@ResponseBody
	public String removeTag(@RequestParam("openIds") String openIds,@RequestParam("ids") String ids, @RequestParam("tag") String tag,
			HttpServletRequest request,Model model){
		String[] idArray = ids.split(",");
		List<Integer> idList = new ArrayList<>();
		for (String id : idArray) {
			if(!"".equals(id)){
				idList.add(Integer.parseInt(id));
			}
		}
		if(idList.size()>0){
			List<WxFlagVo> wxFlags = axdCustLoanService.getWxFlag(idList);
			for(WxFlagVo wxFlag:wxFlags){
				List<String> tt = CommonUtils.parseList(wxFlag.getFlag());
				if(tt.contains(tag)){
					tt.remove(tag);
				}
				if(CommonUtils.isNotEmpty(tt)){
					wxFlag.setFlag("," + org.apache.commons.lang.StringUtils.join(tt, ",") + ",");
				}else{
					wxFlag.setFlag(null);
				}
			}
			
			if (CommonUtils.isNotEmpty(openIds)) {
				List<String> openIdList = CommonUtils.parseList(openIds);
				for(String openid:openIdList){
					if(openid.equals("1")){
						return "error";
					}
				}
				batchDelWechatTag(tag, openIdList, request);
			}else{
				return "error";
			}
			//只更新本地微信标签
			axdCustLoanService.doBatchUpDateFlag(wxFlags);
			return "success";
		}else{
			return "error";
		}
	}
	
	/**
	 * 批量为用户打标签 {"openid_list":[//粉丝列表"ocYxcuAEy30bX0NXmGn4ypqx3tI0",
	 * "ocYxcuBt0mRugKZ7tGAHPnUaOW7Y"],"tagid":134}
	 * 
	 * @param wechatList
	 *            ["ocYxcuAEy30bX0NXmGn4ypqx3tI0",
	 *            "ocYxcuBt0mRugKZ7tGAHPnUaOW7Y"]
	 * @param openIdList
	 *            134
	 * @param request
	 *            r
	 * @return success
	 */
	private String batchAddWechatTag(String tag, List<String> openIdList,
			HttpServletRequest request) {
		// 移动用户分组 同步至微信平台
		SysWxuser sysWxuser = sysWxuserService.selectByWxid(wxId);
		String accessToken = sysWxTokenService.getAccessToken(sysWxuser);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("openid_list", openIdList);
		map.put("tagid", tag);

		String cancelPostJson = JSON.toJSONString(map);
		// 批量为用户打标签
		String result = WxApi.httpsRequestStr(WxApi.BATCH_TAGGING_URL + accessToken, HttpMethod.POST,
				cancelPostJson);
		JSONObject resultJson = JSON.parseObject(result);

		if ("0".equals(resultJson.getString("errcode")) && "ok".equals(resultJson.getString("errmsg"))) {
			logger.info(openIdList.toString() + "打标签" + tag + "成功!!!");
		} else {
			logger.info(openIdList.toString() + "打标签:  errcode:" + resultJson.getString("errcode") + ", errmsg:"
					+ resultJson.getString("errmsg"));
		}
		return "success";
	}
	
	
	/**
	 * 批量为用户取消标签 {"openid_list":["ocYxcuAEy30bX0NXmGn4ypqx3tI0",
	 * "ocYxcuBt0mRugKZ7tGAHPnUaOW7Y"],"tagid":134}
	 * 
	 * @param wechatList
	 *            ["ocYxcuAEy30bX0NXmGn4ypqx3tI0",
	 *            "ocYxcuBt0mRugKZ7tGAHPnUaOW7Y"]
	 * @param openIdList
	 *            134
	 * @param request
	 *            r
	 * @return success
	 */
	private String batchDelWechatTag(String tag, List<String> openIdList,
			HttpServletRequest request) {
		// 移动用户分组 同步至微信平台
		SysWxuser sysWxuser = sysWxuserService.selectByWxid(wxId);
		String accessToken = sysWxTokenService.getAccessToken(sysWxuser);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("openid_list", openIdList);
		map.put("tagid", tag);

		String cancelUrl = getBatchTaggingUrl(WxApi.BATCH_UNTAGGING_URL, accessToken);
		String cancelPostJson = JSON.toJSONString(map);
		// 批量为用户取消标签
		String cancelResult = WxApi.httpsRequestStr(cancelUrl, HttpMethod.POST, cancelPostJson);
		JSONObject cancelResultJson = JSON.parseObject(cancelResult);

		if ("0".equals(cancelResultJson.getString("errcode"))
				&& "ok".equals(cancelResultJson.getString("errmsg"))) {
			logger.info(openIdList.toString() + "取消标签" + tag + "成功!!!");
		} else {
			logger.info(openIdList.toString() + "取消标签:  errcode:" + cancelResultJson.getString("errcode")
					+ ", errmsg:" + cancelResultJson.getString("errmsg"));
		}
		
		return "success";
	}
}
